<template>
	<gui-page :fullPage="true" :isLoading="pageLoading" ref="guiPage">
		<view slot="gBody" class="gui-flex1">
			
			<gui-page-loading ref="guipageloading">
				<text class="gui-block-text gui-text-small gui-text-center gui-color-gray gui-italic"
					style="padding-top:10rpx;">loading</text>
			</gui-page-loading>

			<!-- 搜索框 -->
			<view class="search-bar">
				<view class="search-wrapper">
					<input 
						class="search-input" 
						v-model="searchKeyword" 
						placeholder="搜索聊天记录..."
						@input="onSearchInput"
					/>
					<text class="search-icon">🔍</text>
				</view>
			</view>

			<gui-empty v-if="filteredChats.length==0 && !pageLoading">
				<view slot="img" class="gui-flex gui-rows gui-justify-content-center">
					<image class="gui-empty-img" src="/static/empty_chat.png"></image>
				</view>
				<text slot="text" class="gui-text-small gui-block-text gui-text-center gui-margin-top">暂无聊天记录</text>
			</gui-empty>

			<!-- 聊天列表 -->
			<view class="chat-list" v-if="filteredChats.length > 0">
				<view 
					class="chat-item" 
					v-for="(chat, index) in filteredChats" 
					:key="chat.id"
					@tap="enterChat(chat)"
				>
					<view class="chat-avatar-wrapper">
						<image 
							class="chat-avatar" 
							:src="chat.user_avatar || defaultAvatar"
						></image>
						<view 
							class="unread-badge" 
							v-if="chat.no_read_num > 0"
						>
							{{ chat.no_read_num > 99 ? '99+' : chat.no_read_num }}
						</view>
					</view>
					
					<view class="chat-content">
						<view class="chat-header">
							<text class="chat-name">{{ chat.user_nickname }}</text>
							<text class="chat-time">{{ formatTime(chat.last_message_time) }}</text>
						</view>
						<view class="chat-message">
							<text class="last-message" :class="{ 'unread': chat.no_read_num > 0 }">
								{{ formatLastMessage(chat) }}
							</text>
						</view>
					</view>
					
					
				</view>
			</view>

			<!-- 新建聊天按钮 -->
			<view class="fab-container">
				<button class="fab-button" @tap="showNewChatModal">
					<text class="fab-icon">💬</text>
				</button>
			</view>

			<!-- 新建聊天模态框 -->
			<view class="modal-overlay" v-if="showModal" @tap="hideModal">
				<view class="modal-content" @tap.stop="">
					<view class="modal-header">
						<text class="modal-title">新建聊天</text>
						<text class="modal-close" @tap="hideModal">✕</text>
					</view>
					<view class="modal-body">
						<input 
							class="modal-input" 
							v-model="newChatName" 
							placeholder="输入聊天名称..."
							@confirm="createNewChat"
						/>
						<button class="modal-button primary" @tap="createNewChat">创建</button>
						<button class="modal-button" @tap="hideModal">取消</button>
					</view>
				</view>
			</view>
		</view>
	</gui-page>
</template>

<script>
export default {
	data() {
		return {
			chats: [],
			filteredChats: [],
			searchKeyword: '',
			pageLoading: true,
			showModal: false,
			newChatName: '',
			defaultAvatar: '/static/default_avatar.png',
			searchTimer: null
		}
	},
	
	onLoad() {
		this.$globalMethod();
		this.loadChatList();
	},
	
	onShow() {
		// 页面显示时刷新聊天列表
		this.loadChatList();
	},
	
	onPullDownRefresh() {
		this.loadChatList().then(() => {
			uni.stopPullDownRefresh();
		});
	},
	
	methods: {
		// 加载聊天列表
		loadChatList() {
			return new Promise((resolve) => {
				this.$refs.guipageloading.open();
				
				uni.request({
					url: this.serverUrl + '/api.chat/user_chat_list',
					method: 'GET',
					header: {
						token: this.token
					},
					success: (res) => {
						this.$refs.guipageloading.close();
						this.pageLoading = false;
						
						if (res.data.code === 0) {
							this.chats = res.data.data || [];
							this.filteredChats = [...this.chats];
						} else {
							uni.showToast({
								title: res.data.message || '加载失败',
								icon: 'none'
							});
						}
						resolve();
					},
					fail: (err) => {
						this.$refs.guipageloading.close();
						this.pageLoading = false;
						console.error('加载聊天列表失败:', err);
						
						// 模拟数据（开发测试用）
						this.chats = [
							{
								id: 'chat_1',
								user_nickname: '张教练',
								user_avatar: '',
								last_message: '明天下午3点开始练习',
								last_message_time: Date.now() - 300000,
								no_read_num: 2
							},
							{
								id: 'chat_2',
								user_nickname: '李球友',
								user_avatar: '',
								last_message: '[图片]',
								last_message_time: Date.now() - 3600000,
								no_read_num: 0
							},
							{
								id: 'chat_3',
								user_nickname: '台球群',
								user_avatar: '',
								last_message: '今晚有人一起打球吗？',
								last_message_time: Date.now() - 7200000,
								no_read_num: 5
							}
						];
						this.filteredChats = [...this.chats];
						resolve();
					}
				});
			});
		},
		
		// 搜索输入
		onSearchInput() {
			// 防抖处理
			clearTimeout(this.searchTimer);
			this.searchTimer = setTimeout(() => {
				this.filterChats();
			}, 300);
		},
		
		// 过滤聊天列表
		filterChats() {
			if (!this.searchKeyword.trim()) {
				this.filteredChats = [...this.chats];
			} else {
				const keyword = this.searchKeyword.toLowerCase();
				this.filteredChats = this.chats.filter(chat => {
					// 安全地获取聊天名称
					const chatName = chat.user_nickname || chat.name || '';
					
					// 安全地获取最后一条消息
					let lastMessageContent = '';
					if (chat.last_message) {
						lastMessageContent = chat.last_message;
					} else if (chat.lastMessage && chat.lastMessage.content) {
						lastMessageContent = chat.lastMessage.content;
					}
					
					// 进行搜索匹配
					return chatName.toLowerCase().includes(keyword) ||
						   lastMessageContent.toLowerCase().includes(keyword);
				});
			}
		},
		
		// 进入聊天页面
		enterChat(chat) {
			const title = chat.user_nickname || chat.name || '聊天';
			uni.navigateTo({
				url: `/pages/chat/index?chatId=${chat.user_id}&title=${encodeURIComponent(title)}`
			});
		},
		
		// 删除聊天
		deleteChat(chatId, index) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个聊天记录吗？',
				success: (res) => {
					if (res.confirm) {
						// 发送删除请求
						uni.request({
							url: this.serverUrl + '/api/chat/delete',
							method: 'POST',
							header: {
								token: this.token
							},
							data: {
								chatId: chatId
							},
							success: (res) => {
								if (res.data.code === 0) {
									// 从列表中移除
									this.chats.splice(this.chats.findIndex(c => c.id === chatId), 1);
									this.filteredChats.splice(index, 1);
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: res.data.message || '删除失败',
										icon: 'none'
									});
								}
							},
							fail: (err) => {
								console.error('删除聊天失败:', err);
								// 模拟删除成功
								this.chats.splice(this.chats.findIndex(c => c.id === chatId), 1);
								this.filteredChats.splice(index, 1);
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							}
						});
					}
				}
			});
		},
		
		// 显示新建聊天模态框
		showNewChatModal() {
			this.showModal = true;
			this.newChatName = '';
		},
		
		// 隐藏模态框
		hideModal() {
			this.showModal = false;
			this.newChatName = '';
		},
		
		// 创建新聊天
		createNewChat() {
			const name = this.newChatName.trim();
			if (!name) {
				uni.showToast({
					title: '请输入聊天名称',
					icon: 'none'
				});
				return;
			}
			
			uni.request({
				url: this.serverUrl + '/api/chat/create',
				method: 'POST',
				header: {
					token: this.token
				},
				data: {
					name: name
				},
				success: (res) => {
					if (res.data.code === 0) {
						const newChat = res.data.data;
						this.hideModal();
						// 进入新创建的聊天
						this.enterChat(newChat);
					} else {
						uni.showToast({
							title: res.data.message || '创建失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					console.error('创建聊天失败:', err);
					// 模拟创建成功
					const newChat = {
						id: 'chat_' + Date.now(),
						user_nickname: name,
						user_avatar: '',
						last_message: '',
						last_message_time: Date.now(),
						no_read_num: 0
					};
					this.hideModal();
					this.enterChat(newChat);
				}
			});
		},
		
		// 格式化时间
		formatTime(timestamp) {
			const date = new Date(timestamp);
			const now = new Date();
			const diff = now.getTime() - date.getTime();
			
			if (diff < 60000) { // 1分钟内
				return '刚刚';
			} else if (diff < 3600000) { // 1小时内
				return Math.floor(diff / 60000) + '分钟前';
			} else if (date.toDateString() === now.toDateString()) { // 今天
				return date.getHours().toString().padStart(2, '0') + ':' + 
					   date.getMinutes().toString().padStart(2, '0');
			} else if (diff < 86400000 * 2) { // 昨天
				return '昨天';
			} else if (diff < 86400000 * 7) { // 一周内
				const days = ['日', '一', '二', '三', '四', '五', '六'];
				return '周' + days[date.getDay()];
			} else {
				return (date.getMonth() + 1) + '/' + date.getDate();
			}
		},
		
		// 格式化最后一条消息
		formatLastMessage(chat) {
			if (!chat) return '';
			
			// 处理API返回的格式
			if (chat.last_message) {
				return chat.last_message;
			}
			
			// 处理模拟数据格式
			if (chat.lastMessage) {
				if (chat.lastMessage.type === 'text') {
					return chat.lastMessage.content || '';
				} else if (chat.lastMessage.type === 'image') {
					return '[图片]';
				} else {
					return '[消息]';
				}
			}
			
			return '';
		}
	}
}
</script>

<style scoped>
.search-bar {
	padding: 20rpx 30rpx;
	background-color: #f8f8f8;
}

.search-wrapper {
	position: relative;
	display: flex;
	align-items: center;
}

.search-input {
	flex: 1;
	height: 70rpx;
	padding: 0 20rpx 0 50rpx;
	background-color: #ffffff;
	border-radius: 35rpx;
	border: 1rpx solid #e5e5e5;
	font-size: 28rpx;
}

.search-icon {
	position: absolute;
	left: 20rpx;
	font-size: 28rpx;
	color: #999999;
}

.chat-list {
	flex: 1;
}

.chat-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	background-color: #ffffff;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}

.chat-item:active {
	background-color: #f8f8f8;
}

.chat-avatar-wrapper {
	position: relative;
	margin-right: 20rpx;
}

.chat-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50rpx;
	background-color: #e5e5e5;
}

.unread-badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	min-width: 40rpx;
	height: 40rpx;
	background-color: #ff4444;
	color: #ffffff;
	font-size: 20rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 8rpx;
}

.chat-content {
	flex: 1;
	min-width: 0;
}

.chat-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
}

.chat-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.chat-time {
	font-size: 24rpx;
	color: #999999;
	margin-left: 20rpx;
}

.chat-message {
	display: flex;
	align-items: center;
}

.last-message {
	font-size: 28rpx;
	color: #666666;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 100%;
}

.last-message.unread {
	color: #333333;
	font-weight: bold;
}

.chat-actions {
	margin-left: 20rpx;
}

.delete-btn {
	font-size: 32rpx;
	color: #ff4444;
	padding: 10rpx;
}

.fab-container {
	position: fixed;
	bottom: 100rpx;
	right: 50rpx;
	z-index: 999;
}

.fab-button {
	width: 120rpx;
	height: 120rpx;
	border-radius: 60rpx;
	background-color: #4CAF50;
	border: none;
	box-shadow: 0 4rpx 20rpx rgba(76, 175, 80, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 0;
}

.fab-button:active {
	transform: scale(0.95);
}

.fab-icon {
	font-size: 50rpx;
	color: #ffffff;
}

.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	width: 600rpx;
	background-color: #ffffff;
	border-radius: 20rpx;
	overflow: hidden;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.modal-close {
	font-size: 32rpx;
	color: #999999;
	padding: 10rpx;
}

.modal-body {
	padding: 30rpx;
}

.modal-input {
	width: 100%;
	height: 80rpx;
	padding: 0 20rpx;
	border: 1rpx solid #e5e5e5;
	border-radius: 10rpx;
	font-size: 28rpx;
	margin-bottom: 30rpx;
	box-sizing: border-box;
}

.modal-button {
	width: 100%;
	height: 80rpx;
	border-radius: 10rpx;
	border: none;
	font-size: 28rpx;
	margin-bottom: 20rpx;
	background-color: #f0f0f0;
	color: #333333;
}

.modal-button.primary {
	background-color: #4CAF50;
	color: #ffffff;
}

.modal-button:last-child {
	margin-bottom: 0;
}
</style> 